<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>webSocket</title>
    <style>
        .output {
            width: 100%;
            position: relative;
        }

        .output-contant {
            width: 300px;
            height: 600px;
            border: 1px solid black;
            position: absolute;
            left: 50%;
            margin-top: 50px;
            margin-left: -150px;
        }

        .sendMsgIput {
            width: 300px;
            border-top: 1px solid black;
            position: absolute;
            bottom: 0;
        }

        .sendButton {
            display: inline-block;
            width: 50px;
            background-color: skyblue;
        }
    </style>
</head>

<body>
    <div class="output">
        <div class="output-contant">
            <div class="sendMsgIput">
                <input type="text" id="msgText" value="" />
                <div class="sendButton" onClick="send(document.getElementById('msgText').value)">
                    发送
                </div>
            </div>
        </div>
    </div>
    <script>
        let sendBtn = document.querySelector(".sendButton")
        //let msgText = document.getElementById("msgText")
        let outputContant = document.querySelector(".output-contant")


        function send(msg) {
            let mmsg = msg || "阿巴阿巴阿巴"
            ws.send(msg)
        }
        var ws = new WebSocket('ws://localhost:8089')
        ws.onopen = function (e) {
            console.log("链接服务器")
            ws.send("hello") //发送成功，触发onmessage
        }
        ws.onclose = function (e) {
            var code = event.code;
            var reason = event.reason;
            var wasClean = event.wasClean;

            console.log("关闭链接")
            console.log(`111 ${code}  ${reason}  ${wasClean}`)
        }
        ws.onerror = function () {
            console.log("链接出错")
        }
        ws.onmessage = function (e) {
            console.log("接收到的消息为:" + e.data)
            outputContant.innerHTML += `<p>${e.data}</p>`
        }
    </script>
</body>

</html>